package t10086.WorkThread.Shared;

import t10086.WorkThread.Shared.Client.Client;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ClientMap {
    private static final Map<InetSocketAddress, Client> clients = new ConcurrentHashMap<>();
    private static final Map<String,InetSocketAddress> addresses = new ConcurrentHashMap<>();
    public static InetSocketAddress getAddress(String address) {
        if (addresses.containsKey(address))
            return addresses.get(address);
        return null;
    }
    public static void removeClientBySerialNumber(String serialNumber) {
        InetSocketAddress address = getAddress(serialNumber);
        removeClient(address);
    }
    public static void putAddress(String address,InetSocketAddress addr) {
        addresses.put(address, addr);
    }
    public  static Map<InetSocketAddress, Client> getClients() {
        return new ConcurrentHashMap<>(clients);
    }
    public static Client removeClient(InetSocketAddress inetSocketAddress) {
        if(inetSocketAddress == null){
            return null;
        }
        Client client = clients.remove(inetSocketAddress);
        if (client == null)
            return null;
        client.close();
        return client;
    }
    public static void addClient(InetSocketAddress inetSocketAddress, Client client) {
        clients.putIfAbsent(inetSocketAddress, client);
    }
    public static Client getClient(InetSocketAddress inetSocketAddress) {
        return clients.get(inetSocketAddress);
    }
    public static void removeAllClients() {
        clients.clear();
        addresses.clear();
    }
}
